<template>
  <div class="koi-flex">
    <KoiCard>
      <!-- 搜索条件 -->
      <el-form v-show="showSearch" :inline="true">
        <el-form-item label="角色昵称" prop="roleId">
          <el-select v-model="searchParams.roleId" filterable placeholder="请选择角色" clearable style="width: 200px"
            @keyup.enter.native="handleListPage">
            <!-- <el-option label="请选择角色" value="" /> -->
            <el-option v-for="item in roleOptions" :key="item.roleId" :label="item.roleName" :value="item.roleId" />
          </el-select>
        </el-form-item>
        <el-form-item label="用户名称" prop="nickname">
          <el-input placeholder="请输入用户名称" v-model="searchParams.nickname" clearable style="width: 200px"
            @keyup.enter.native="handleListPage"></el-input>
        </el-form-item>
        <el-form-item label="手机号码" prop="phone">
          <el-input placeholder="请输入手机号码" v-model="searchParams.phone" clearable style="width: 200px"
            @keyup.enter.native="handleListPage"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="search" plain v-debounce="handleSearch">搜索</el-button>
          <el-button type="danger" icon="refresh" plain v-throttle="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>

      <!-- 表格头部按钮 -->
      <el-row :gutter="10">
        <el-col :span="1.5" v-auth="['system:role:add']">
          <el-button type="primary" icon="plus" plain @click="handleAdd()">新增用户</el-button>
        </el-col>
        <KoiToolbar v-model:showSearch="showSearch" @refreshTable="handleListPage"></KoiToolbar>
      </el-row>

      <br />
      <!-- 数据表格 :data="tableList" -->
      <el-table v-loading="loading" border :data="tableList" empty-text="暂时没有数据哟🌻">
        <el-table-column label="登录账号" prop="account" align="center" :show-overflow-tooltip="true"></el-table-column>
        <el-table-column label="用户名称" prop="nickname" align="center" :show-overflow-tooltip="true"></el-table-column>
        <el-table-column label="手机号码" prop="phone" align="center" :show-overflow-tooltip="true"></el-table-column>
        <el-table-column label="用户类型" prop="role" align="center">
          <template #default="scope">
            <KoiTag :tagOptions="userTypeOptions" :value="scope.row.role._id"></KoiTag>
          </template>
        </el-table-column>
        <el-table-column label="拥有服务" prop="role" align="center" :show-overflow-tooltip="true">
          <template #default="scope">
            {{
              scope.row.role.roleTag && scope.row.role.roleTag.length > 0 ? '是' : '否'
            }}
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" fixed="right" v-auth="['system:role:update', 'system:role:delete']">
          <template #default="{ row }">
            <el-tooltip content="重置密码" placement="top">
              <el-button type="primary" icon="Key" circle plain @click="handleReset(row)"
                v-auth="['system:role:update']"></el-button>
            </el-tooltip>
            <el-tooltip content="删除用户" placement="top">
              <el-button type="danger" icon="Delete" circle plain @click="handleDelete(row)"
                v-auth="['system:role:delete']"></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
      <br />

      <!-- 分页 -->
      <el-pagination background v-model:current-page="searchParams.page" v-model:page-size="searchParams.pageSize"
        v-show="total > 0" :page-sizes="[10, 20, 50, 100, 200]" layout="total, sizes, prev, pager, next, jumper"
        :total="total" @size-change="handleListPage" @current-change="handleListPage" />

      <!-- 添加 -->
      <KoiDialog ref="koiDialogRef" :title="title" height="310" @koiConfirm="handleConfirm" @koiCancel="handleCancel"
        :loading="confirmLoading">
        <template #content>
          <el-form ref="formRef" :rules="rules" :model="form" label-width="80px">
            <el-row>
              <el-col :xs="{ span: 24 }" :sm="{ span: 24 }">
                <el-form-item label="用户名称" prop="nickname">
                  <el-input v-model="form.nickname" placeholder="请输入用户名称" clearable />
                </el-form-item>
              </el-col>
              <el-col :xs="{ span: 24 }" :sm="{ span: 24 }">
                <el-form-item label="用户类型" prop="roleId">
                  <el-select placeholder="请选择用户类型" filterable v-model="form.roleId" clearable>
                    <el-option v-for="item in userTypeOptions" :key="item.dictValue" :label="item.dictLabel"
                      :value="item.dictValue" />
                  </el-select>
                </el-form-item>
              </el-col>

              <el-col :xs="{ span: 24 }" :sm="{ span: 24 }">
                <el-form-item label="手机号码" prop="phone">
                  <el-input v-model="form.phone" placeholder="请输入手机号码"></el-input>
                </el-form-item>
              </el-col>
              <el-col :xs="{ span: 24 }" :sm="{ span: 24 }">
                <el-form-item label="登录账号" prop="account">
                  <el-input v-model="form.account" placeholder="请输入用户名称" clearable />
                </el-form-item>
              </el-col>
              <el-col :xs="{ span: 24 }" :sm="{ span: 24 }">
                <el-form-item label="登录密码" prop="password">
                  <el-input v-model="form.password" placeholder="请输入用户名称" clearable />
                </el-form-item>
              </el-col>

            </el-row>
          </el-form>
        </template>
      </KoiDialog>
    </KoiCard>
  </div>
</template>

<script setup lang="ts" name="userPage">
// 已使用字典案例
import { nextTick, ref, reactive, onMounted } from "vue";
// @ts-ignore
import {
  koiNoticeSuccess,
  koiNoticeError,
  koiMsgError,
  koiMsgBox,
  koiMsgBoxPrompt
} from "@/utils/koi.ts";
// @ts-ignore
import { getAllUser, getAllRole, deleteUser, updateUserPassword, addUser, listPage, getById, add, update, deleteById, batchDelete, updateStatus } from "@/api/system/user/index.ts";
// @ts-ignore
import { listDataByType } from "@/api/system/dict/data/index.ts";

// 数据表格加载页面动画
const loading = ref(false);
/** 是否显示搜索表单 */
const showSearch = ref<boolean>(true); // 默认显示搜索条件
// 数据表格数据
const tableList = ref<any>([]);

// 角色数据
const roleOptions = ref<any>([]);

// 查询参数
const searchParams = ref({
  page: 1, // 第几页
  pageSize: 10, // 每页显示多少条

  roleId: "",
  nickname: "",
  phone: ""
});

const total = ref<number>(0);

// 重置搜索参数
const resetSearchParams = () => {
  searchParams.value = {
    page: 1,
    pageSize: 10,
    roleId: "",
    nickname: "",
    phone: ""
  };
};

/** 搜索 */
const handleSearch = () => {
  searchParams.value.page = 1;
  handleListPage();
};

/** 重置 */
const resetSearch = () => {
  resetSearchParams();
  handleListPage();
};

/** 数据表格 */
const handleListPage = async () => {
  try {
    loading.value = true;
    tableList.value = []; // 重置表格数据

    function removeEmptyKeys(obj: any) {
      Object.keys(obj.value).forEach(key => {
        if (obj.value[key] === "" || obj.value[key] === null || obj.value[key] === undefined) {
          delete obj.value[key];
        }
      });
    }

    removeEmptyKeys(searchParams);

    const res: any = await getAllUser(searchParams.value);
    tableList.value = res.data;
    total.value = res.count;
  } catch (error) {
    console.log(error);
    total.value = 0;
    koiNoticeError("列表数据查询失败，请刷新重试");
  } finally {
    loading.value = false;
  }
};

const userTypeOptions = ref<any>([]);

const handleRolelist = async () => {

  try {
    const res: any = await getAllRole({})
    roleOptions.value = res.data.map((item: any) => {
      return {
        roleId: item.id,
        roleName: item.name
      }
    });
    userTypeOptions.value = res.data.map((item: any) => {
      return {
        dictLabel: item.name,
        dictValue: item.id,
        dictTag: "primary",
        dictColor: ""
      }
    });
  } catch (error) {
    console.log(error);
    koiNoticeError("角色数据查询失败，请刷新重试");
  }

};

onMounted(() => {
  // 获取数据表格数据
  handleListPage();
  handleRolelist();
});

/** 添加 */
const handleAdd = () => {
  // 打开弹出框
  koiDialogRef.value.koiOpen();
  // 重置表单
  resetForm();
  // 标题
  title.value = "新增用户";
};

/**重置密码 */
const handleReset = (row: any) => {
  koiMsgBoxPrompt('请输入新密码').then((value: any) => {
    koiMsgBox("您确认需要重置用户[" + row.nickname + "]的密码么？")
      .then(() => {
        updateUserPassword(row.id, {
          password: value.value
        })
          .then(() => {
            koiNoticeSuccess("重置成功");
          })
          .catch(() => {
            koiNoticeError("重置失败，请重试");
          });
      })
  })
};

/** 添加 AND 修改抽屉 */
const koiDialogRef = ref();
// 标题
const title = ref("");
// form表单Ref
const formRef = ref<any>();

// form表单
let form = ref<any>({
  nickname: "",
  roleId: "",
  phone: "",
  account: "",
  password: "",
  detail: {}
});

/** 清空表单数据 */
const resetForm = () => {
  // 等待 DOM 更新完成
  nextTick(() => {
    if (formRef.value) {
      // 重置该表单项，将其值重置为初始值，并移除校验结果
      formRef.value.resetFields();
    }
  });
  form.value = {
    nickname: "",
    roleId: "",
    phone: "",
    account: "",
    password: "",
    detail: {}
  };
};

/** 表单规则 */
const rules = reactive({
  nickname: [{ required: true, message: "请输入用户名称", trigger: "blur" }],
  roleId: [{ required: true, message: "请选择用户类型", trigger: "change" }],
  phone: [{ required: true, message: "请输入手机号码", trigger: "blur" }],
  account: [{ required: true, message: "请输入登录账号", trigger: "blur" }],
  password: [{ required: true, message: "请输入登录密码", trigger: "blur" }]
});

// 确定按钮是否显示loading
const confirmLoading = ref(false);
/** 确定  */
const handleConfirm = () => {
  if (!formRef.value) return;
  confirmLoading.value = true;
  (formRef.value as any).validate(async (valid: any) => {
    if (valid) {

      try {
        await addUser(form.value);
        koiNoticeSuccess("添加成功");
        confirmLoading.value = false;
        koiDialogRef.value.koiQuickClose();
        resetForm();
        handleListPage();
      } catch (error) {
        console.log(error);
        confirmLoading.value = false;
        koiNoticeError("添加失败，请刷新重试");
      }

    } else {
      koiMsgError("验证失败，请检查填写内容");
      confirmLoading.value = false;
    }
  });
};

/** 取消 */
const handleCancel = () => {
  koiDialogRef.value.koiClose();
};

/** 删除 */
const handleDelete = (row: any) => {
  koiMsgBox("您确认需要删除用户名称[" + row.nickname + "]么？")
    .then(async () => {
      try {
        await deleteUser(row.id)
        handleListPage();
        koiNoticeSuccess("删除成功");
      } catch (error) {
        handleListPage();
        koiNoticeError("删除失败，请刷新重试");
      }
    })
};
</script>

<style lang="scss" scoped>
// 穿梭框高度调整
:deep(.el-transfer-panel__body) {
  height: 400px;
}
</style>